// pages/address/add.js
const api = require("../../request/api")
const request = require("../../request/request")
const util = require("../../utils/util")
const App = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    styledata: {
      "bg_color": "white",
      "color": "#000",
      "leftflag": true,
      "homeflag": true,
      "name": "添加地址"
    },
    name_value: '',
    phone_value: '',
    address_value: '',
    street_value: '',  //街道 门牌号

    latitude: 0,
    longtitude: 0,
    uid: '',
    default_value: false,
    options: {},
    current_local_address: null,

    cityTitle: '请选择',

    provinceVisible: false,
    cityVisible: false,
    regionVisible: false,
    streetVisible: false,

    // 选择器绑定值，绑定数字value
    provinceValue: [],
    cityValue: [],
    regionValue: [],
    streetValue: [],

    // input绑定值，绑定中文名
    provinceName: '',
    cityName: '',
    regionName: '',
    streetName: '',

    provinces: [],
    citys: [],
    regions: [],
    streets: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    this.init_data(options)

    let pro = await this.getCityData()
    this.setData({
      provinces: pro,
      provinceValue: [pro[0].value]
    })

    let city = await this.getCityData(pro[0].value)
    this.setData({
      citys: city,
      cityValue: [city[0].value]
    })
    
    let region = await this.getCityData(city[0].value)
    this.setData({
      regions: region,
      regionValue: [region[0].value]
    })

    let street = await this.getCityData(region[0].value)
    this.setData({
      streets: street,
      streetValue: [street[0].value]
    })
  },

  init_data(options) {
    this.setData({
      uid: App.globalData.uid || util.getAppValue('userInfo').uid,
      options
    })
  },

  // 获取省市区方法
  async getCityData(code = '') {
    let res = await request.post(api.getcity, { code })
    if (res.code == 0) {
      let conData = res.con
      conData.forEach(item => {
        item.label = item.name
        item.value = item.code
      });
      return conData
    } else {
      util.showFail('地区信息获取失败')
    }
  },

  // 省份
  showprovincePicker() {
    this.setData({
      provinceVisible: true,
    });
  },
  
    // 省会改变 下级全部制空，重新请求数据
  async onPickerChange1(e) {
    const { key } = e.currentTarget.dataset;
    const { value, label } = e.detail;

    console.log('picker change:', e.detail);
    this.setData({
      provinceVisible: false,
      provinceValue: value,
      provinceName: label[0],

      citys: [],
      regions: [],
      streets: [],

      cityValue: [],
      cityName: '',

      regionValue: [],
      regionName: '',

      streetValue: [],
      streetName: ''
    });

    let data = await this.getCityData(value[0])
    this.setData({
      citys: data
    })
  },

  onPickerCancel1(e) {
    const { key } = e.currentTarget.dataset;
    console.log(e, '取消');
    console.log('picker1 cancel:');
    this.setData({
      provinceVisible: false,
    });
  },

  // 城市
  showcityPicker() {
    this.setData({
      cityVisible: true,
    });
  },

  async onPickerChange2(e) {
    console.log('确定');
    const { key } = e.currentTarget.dataset;
    const { value, label } = e.detail;

    console.log('picker change:', e.detail);
    this.setData({
      cityVisible: false,
      cityValue: value,
      cityName: label[0],

      regions: [],
      streets: [],

      regionValue: [],
      regionName: '',

      streetValue: [],
      streetName: ''
    });

    let data = await this.getCityData(value[0])
    this.setData({
      regions: data
    })
  },

  onPickerCancel2(e) {
    const { key } = e.currentTarget.dataset;
    console.log(e, '取消');
    console.log('picker1 cancel:');
    this.setData({
      cityVisible: false,
    });
  },

  // 区县
  showregionPicker() {
    this.setData({
      regionVisible: true,
    });
  },

  async onPickerChange3(e) {
    console.log('确定');
    const { key } = e.currentTarget.dataset;
    const { value, label } = e.detail;
    console.log('picker change:', e.detail);
    this.setData({
      regionVisible: false,
      regionValue: value,
      regionName: label[0],

      streets: [],

      streetValue: [],
      streetName: ''
    });

    let data = await this.getCityData(value[0])
    this.setData({
      streets: data
    })
  },

  onPickerCancel3(e) {
    const { key } = e.currentTarget.dataset;
    console.log(e, '取消');
    console.log('picker1 cancel:');
    this.setData({
      regionVisible: false,
    });
  },

  // 街道
  showstreetPicker() {
    this.setData({
      streetVisible: true,
    });
  },

  onPickerChange4(e) {
    console.log('确定');
    const { key } = e.currentTarget.dataset;
    const { value, label } = e.detail;
    console.log('picker change:', e.detail);
    this.setData({
      streetVisible: false,
      streetValue: value,
      streetName: label[0],
    });
  },

  onPickerCancel4(e) {
    const { key } = e.currentTarget.dataset;
    console.log(e, '取消');
    console.log('picker1 cancel:');
    this.setData({
      streetVisible: false,
    });
  },

  // 发送请求添加新地址
  save_address() {
    let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    let that = this
    if (that.data.name_value == '') {
      util.showToast('请输入收货人姓名')
      return
    }
    if (!reg.test(that.data.phone_value)) {
      util.showToast('请输入正确号码')
      return
    }
    if (this.data.provinceName == '') {
      util.showToast('请选择省份信息')
      return
    }
    if (this.data.cityName == '') {
      util.showToast('请选择城市信息')
      return
    }
    if (this.data.regionName == '' && this.data.regions.length > 0) {
      util.showToast('请选择区县信息')
      return
    }
    if (that.data.address_value == '') {
      util.showToast('请输入您的详细地址')
      return
    }
    let params = {
      uid: that.data.uid,
      name: that.data.name_value,
      mobile: that.data.phone_value,

      province: that.data.provinceValue[0],  //province area_id
      city: that.data.cityValue[0],         //city area_id
      region: that.data.regionValue[0],    //region area_id
      area: that.data.regionValue[0],    //region area_id
      town: that.data.streetValue[0],

      province_name: that.data.provinceName,
      city_name: that.data.cityName,
      region_name: that.data.regionName,
      town_name: that.data.streetName,

      address: that.data.address_value,
      is_default: that.data.default_value ? 1 : 0,

      // street_value: that.data.street_value,
    }

    wx.request({
      url: api.addressadd,
      method: 'POST',
      header: { 'content-type': 'application/json' },
      data: params,
      success(res) {
        if (res.code == 0) {
          util.showToast('保存成功！')
          wx.navigateBack({
            delta: 1
          })
        } else {
          util.showToast('地址添加失败，请重试')
        }
      }
    })
  },

  // 选择微信地址
  wx_choose_address() {
    const that = this
    wx.chooseAddress({
      success: async (result) => {
        // console.log(result);
        // 设置到表格上 微信地址返回结果没有地区码
        console.log('result', result);
        this.setData({
          name_value: result.userName,
          phone_value: result.telNumber,

          provinceName: result.provinceName,
          cityName: result.cityName,
          regionName: result.countyName,
          address_value: result.detailInfo,
        })

        // 省份
        let provinceData = await that.getCityData()
        provinceData.forEach((item) => {
          let oo = result.provinceName.indexOf(item.label)
          if (oo != -1) {
            that.setData({
              provinceValue: [item.value],
              provinceName: item.label
            })
            return
          }
        });

        // 城市
        let cityData = await that.getCityData(this.data.provinceValue[0])
        that.setData({
          citys: cityData
        })
        cityData.forEach((item) => {
          let oo = result.cityName.indexOf(item.label)
          if (oo != -1) {
            that.setData({
              cityValue: [item.value],
              cityName: item.label
            })
            return
          }
        });

        // 区县
        let regionData = await that.getCityData(this.data.cityValue[0])
        that.setData({
          regions: regionData
        })
        regionData.forEach((item) => {
          let oo = result.countyName.indexOf(item.label)
          if (oo != -1) {
            that.setData({
              regionValue: [item.value],
              regionName: item.label
            })
            return
          }
        });

        // 街道
        let streetData = await that.getCityData(this.data.regionValue[0])
        that.setData({
          streets: streetData
        })
      },
    })
  },

  // 编辑是否为默认地址
  switching(e) {
    this.setData({
      default_value: e.detail.value
    })
  },

  address_input(e) {
    this.setData({
      address_value: e.detail.value
    })
  },
  street_input(e) {
    this.setData({
      street_value: e.detail.value
    })
  },
  name_input(e) {
    this.setData({
      name_value: e.detail.value
    })
  },
  phone_input(e) {
    this.setData({
      phone_value: e.detail.value
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})